<?php
	//缓冲类
	class cache
	{
		var $dir = '';

		function cache( $dir )
		{
			$this->dir = $dir;
		}

		function save( $key, $data, $php = true )
		{
			$file = $this->name( $key );
			$content = $php ? '<?php $__cache__ = ' . var_export( $data, true ) . '; ?>' : $data;
			return file_put_contents( $file, $content, LOCK_EX );
		}

		function load( $key, $expire = 0, $php = true )
		{
			$file = $this->name( $key );

			if ( is_file( $file ) && ( $expire < 1 || ( time() - filemtime( $file ) <= $expire ) ) )
			{
				if ( $php )
				{
					require $file;
					return $__cache__;
				}
				else
				{
					return file_get_contents( $file );
				}
			}
			else
			{
				return false;
			}
		}

		function clear( $key )
		{
			$file = $this->name( $key );
			return is_file( $file ) ? unlink( $file ) : true;
		}

		function name( $key )
		{
			$crc32 = sprintf( '%u', crc32( $key ) );
			$length = strlen( $key );
			$dir = $this->dir . chunk_split( $crc32, 3, '/' );
			if ( ! is_dir( $dir ) ) mkdir( $dir, 0777, true );
			return $dir . DIRECTORY_SEPARATOR . $crc32 . ord( $key[0] ) . $length . ord( $key[$length-1] ) . '.php';
		}
	}
?>